package com.tmpt.service.impl;

import com.googlecode.genericdao.search.Search;
import com.inspiresoftware.lib.dto.geda.assembler.DTOAssembler;
import com.tmpt.beans.*;
import com.tmpt.dao.impl.A1TemplateTableDao;
import com.tmpt.dao.intf.*;
import com.tmpt.dto.*;
import com.tmpt.enums.DataLimitType;
import com.tmpt.service.IMenuService;
import com.tmpt.service.IOperationlogService;
import com.tmpt.utils.Config;
import com.tmpt.utils.StringUtils;
import com.tmptSource.dto.A3jeeCodingDto;
import com.tmptSource.service.intf.IA3jeeCodingService;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Transactional(propagation=Propagation.REQUIRED)
public class MenuService implements IMenuService {
	@Resource IA3MenuDao a3MenuDao;
	@Resource IA3MenuMyDao a3MenuMyDao;
	@Resource IA2RoleDao a2RoleDao;
	@Resource IA2UserDao a2UserDao;
	@Resource IOperationlogService operationlogService;
	@Resource
	IA1TemplateTableDao a1TemplateTableDao;
	@Resource
	IA1TemplateColumnDao a1TemplateColumnDao;
	@Resource
	IA3jeeCodingService a3jeeCodingService;

	private Logger log = Logger.getLogger(this.getClass());


	@Override
	public Result addMenu(A3MenuDto menuDto, long parentId) {
		Result result = new Result();

		A3Menu menu = new A3Menu();
		DTOAssembler dtoAssembler = DTOAssembler.newAssembler(A3MenuDto.class);
		dtoAssembler.assembleEntity(menuDto, menu, null, null);

		//找上级岗位
		A3Menu parentMenu = null;
		if(parentId!=0){
			parentMenu = a3MenuDao.fetch(parentId);
		}
		//添加数据
		menu.setA3MenuParent(parentMenu);
		a3MenuDao.create(menu);

		return result.success();
	}

	@Override
	public Result<A3MenuDto> queryMenuById(long id) {
		Result<A3MenuDto> result = new Result();

		A3Menu menu = a3MenuDao.fetch(id);
		A3MenuDto menuDto = new A3MenuDto();
		DTOAssembler dtoAssembler = DTOAssembler.newAssembler(A3MenuDto.class);
		dtoAssembler.assembleDto(menuDto, menu, null, null);
		result.setResultObj(menuDto);

		return result.success();
	}

	@Override
	public Result<A3MenuDto> modifyMenuById(A3MenuDto menuDto) {
		Result<A3MenuDto> result = new Result();

		A3Menu menu = a3MenuDao.fetch(menuDto.getId());
		menu.setText(menuDto.getText());
		menu.setSort(menuDto.getSort());
		menu.setUrl(menuDto.getUrl());
		menu.setType(menuDto.getType());
		menu.setKeyRandom(menuDto.getKeyRandom());
		menu.setHasDataLimit(menuDto.getHasDataLimit());
		menu.setIconClass(menuDto.getIconClass());
		menu.setSort(menuDto.getSort());
		a3MenuDao.update(menu);

		return result.success();
	}

	@Override
	public Result<A3MenuDto> removeMenuById(long id) {
		Result<A3MenuDto> result = new Result();

		A3Menu menu = a3MenuDao.fetch(id);
		menu.setDeleteFlag(1);
		a3MenuDao.update(menu);

		return result.success();
	}

	/**
	 * 查询菜单tree结构
	 * @param paramMap :menuType menuType的最小级（0=menu; 10=leave menu; 20=function 30=function url）；如传入20，则递归查询type<=20
	 * @return
	 */
	@Override
	public Result<A3MenuDto> queryMenus4RoleConf(Map<String,Object> paramMap) {
		String id = (String)paramMap.get("id");
		//MenuFromRoleMag 权限分配: 在权限分配页面希望子节点是"查询"这一级别
		//MenuMag 菜单管理
		String from = (String)paramMap.get("from");
		Result<A2PostDto> result = new Result();

		Search search = new Search();
		if(StringUtils.isNull(id)){
			search.addFilterEmpty("a3MenuParent");
		}else {
			search.addFilterEqual("a3MenuParent.id", id);
		}
		search.addFilterEqual("deleteFlag", 0);
		search.addSort("sort", false);
		List<A3Menu> menuList = a3MenuDao.search(search);

		//递归生成树，存储在jsonObject里
		JSONObject jsonObject = new JSONObject();
		genMenuJsonTree(jsonObject, menuList, from);
		JSONArray jsonArray = jsonObject.getJSONArray("children");
		List list = jsonArray.toList();
		String menuJson = jsonArray.toString();

		result.getResultMap().put("menuJson", menuJson);
		result.getResultMap().put("list", list);
		//.out.println("---------------menuJson:" + menuJson);
		return result.success();
	}

	/**
	 * 递归Post生成树
	 */
	private void genMenuJsonTree(JSONObject jsonObject,List<A3Menu> menuList,String from){
		//.out.println("-=====>from:" + from);
		JSONArray jsonArray = new JSONArray();
		jsonObject.put("children", jsonArray);

		for(A3Menu menu: menuList){
			long id = menu.getId();
			long menuParentId = 0;
			if(menu.getA3MenuParent()!=null){
				menuParentId = menu.getA3MenuParent().getId();
			}
			int deleteFlag = menu.getDeleteFlag();
			if(deleteFlag==1){
				continue;
			}
			String text = menu.getText();
			String url = menu.getUrl();
			int type = menu.getType();
			int hasDataLimit = menu.getHasDataLimit();
			String iconClass = menu.getIconClass();
			int sort = menu.getSort();
			String keyRandom = menu.getKeyRandom()==null?"":menu.getKeyRandom();

			//json
			JSONObject jsonObjectSon = new JSONObject();
			jsonObjectSon.put("id",id);
			jsonObjectSon.put("menuParentId",menuParentId);
			jsonObjectSon.put("text",text);
			jsonObjectSon.put("name",text);
			jsonObjectSon.put("url", url==null?"":url);
			jsonObjectSon.put("type", type);
			jsonObjectSon.put("hasDataLimit", hasDataLimit);
			jsonObjectSon.put("iconClass", iconClass);
			jsonObjectSon.put("sort", sort);
			jsonObjectSon.put("keyRandom", keyRandom);
			if("MenuMag".equals(from)){
				if(type==20) {
					jsonObjectSon.put("state", "closed");
				}else{
					jsonObjectSon.put("state", "closed");
				}
			}


			//菜单上的属性
			JSONObject joAttr = new JSONObject();
			//joAttr.put("checkState", "true");
			joAttr.put("type", type);
			joAttr.put("url", url==null?"":url);
			joAttr.put("hasDataLimit", hasDataLimit);
			jsonObjectSon.put("attributes", joAttr);
			jsonArray.put(jsonObjectSon);

			List<A3Menu> menuSonList = menu.getA3MenuSonList();
			if(menuSonList.size()==0){continue;}

			if("MenuFromRoleMag".equals(from)){
				if(type >= 20){continue;}
			}
			if("MenuMag".equals(from)){
				if(type >= 30){continue;}
			}
			//只显示1级菜单
			if("OneLevel".equals(from)){
				if(type >= 0){continue;}
			}


			genMenuJsonTree(jsonObjectSon, menuSonList, from);

			//多级上级菜单情况下，查询所有上级菜单，只显示第一级上级菜单，暂未处理
			/*List<A3Menu> menuSonList = menu.getA3MenuSonList();
			if(menuSonList==null || menuSonList.size()==0){continue;}

			boolean sonHasThisMenu = false;
			for(A3Menu a3MenuSon : menuSonList){
				if(a3MenuSon.getType() == menuType){
					sonHasThisMenu = true;
				}
			}
			if(type == menuType && !sonHasThisMenu){continue;}

			genMenuJsonTree(jsonObjectSon, menuSonList, menuType);*/
		}
	}


	@Override
	public Result bindRole_Menu(long roleId, String roleJsonArray, A1OperationlogDto logDto) {
		Result result = new Result();
		A2Role a2Role = a2RoleDao.fetch(roleId);

		//角色下已存在菜单，先删除这些菜单
		if(a2Role.getA3MenuMyList().size()>0){
			for(A3MenuMy menu1My : a2Role.getA3MenuMyList()){
				a3MenuMyDao.deleteEntity(menu1My);
			}
		}

		JSONArray jsonArray = new JSONArray(roleJsonArray);
		for(int i=0;i<jsonArray.length();i++){
			JSONObject jsonObject = jsonArray.optJSONObject(i);
			Long menuId = jsonObject.optLong("menuId");
			Long menuParentId = jsonObject.optLong("menuParentId");
			int dataLimitType = jsonObject.optInt("dataLimitType");
			int childrenLength = jsonObject.optInt("childrenLength");
			int type = jsonObject.optInt("type");
			//type=20, 是页面功能button, 只保存这个。上级不能保存，防止加入新button后，页面显示是选中状态
			if( (type==10 && childrenLength==0)//子菜单直接打开一个有查询功能的页面，无查询button
					|| type==20) {
				A3MenuMy menuMy = new A3MenuMy();
				menuMy.setA2Role(a2Role);
				menuMy.setA3Menu(a3MenuDao.fetch(menuId));
				menuMy.setDataLimitType(dataLimitType);
				a3MenuMyDao.create(menuMy);
			}
		}

		//日志
		if(logDto != null){
			logDto.setLogTypeName("后台：员工管理");
			logDto.setDescription("绑定角色 和 菜单：roleId:"+roleId);
			operationlogService.addOperationlog(logDto);
		}
		return result.success();
	}

	@Override
	public Result queryMenus4RoleConfByRoleId(long roleId) {
		Result result = new Result();
		JSONArray jsonArr = new JSONArray();
		//取某角色拥有的 菜单
		A2Role a2Role = a2RoleDao.fetch(roleId);
		List<A3MenuMy> a3MenuMyList = a2Role.getA3MenuMyList();
		for(A3MenuMy menuMy: a3MenuMyList){
			A3Menu menu = menuMy.getA3Menu();
			long menuId = menu.getId();
			int deleteFlag = menu.getDeleteFlag();
			if(deleteFlag==1){continue;}
			int dataLimitType = menuMy.getDataLimitType();
			JSONObject jo = new JSONObject();
			jo.put("menuId", menuId);
			jo.put("dataLimitType", dataLimitType);
			jsonArr.put(jo);
		}

		String menu4RoleConfByRoleIdJson = jsonArr.toString();
		//.out.println("menu4RoleConfByRoleIdJson:" + menu4RoleConfByRoleIdJson);
		result.getResultMap().put("menu4RoleConfByRoleIdJson", menu4RoleConfByRoleIdJson);
		return result.success();
	}


	//[{"text":"系统基本信息管理",'state':'closed',"children":[{"text":"修改密码","attributes":{"url":"user/changePwd.jsp"}},{"text":"修改个人资料","attributes":{"url":"user/changeMyInfo.jsp"}},{"text":"部门管理","attributes":{"url":"user/deptMag.jsp"}},{"text":"后台用户管理","attributes":{"url":"user/userList.jsp"}},{"text":"角色权限配置","attributes":{"url":"user/cfgRoleAuth.jsp"}},{"text":"操作日志查询","attributes":{"url":"log/logList.jsp"}},{"text":"模板页面管理","attributes":{"url":"template/tableList.jsp"}}]},{"text":"客户管理",'state':'closed',"children":[{"text":"个人用户列表","attributes":{"url":"user/customerList.jsp"}}]},{"text":"商户管理",'state':'closed',"children":[{"text":"代理商管理","attributes":{"url":"merchant/merchantAgentList.jsp"}},{"text":"费率管理","attributes":{"url":"merchant/merchantRateList.jsp"}},{"text":"商户增加","attributes":{"url":"merchant/merchantInfoAdd.jsp"}},{"text":"商户列表","attributes":{"url":"merchant/merchantInfoList.jsp"}}]},{"text":"商户平台管理",'state':'closed',"children":[]},{"text":"合作银行管理",'state':'closed',"children":[{"text":"合作银行增加","attributes":{"url":"bankpatcoop/bankPatCoopAdd.jsp"}},{"text":"合作银行列表","attributes":{"url":"bankpatcoop/bankPatCoopList.jsp"}}]},{"text":"退货/取消管理",'state':'closed',"children":[{"text":"退货/取消管理","attributes":{"url":"orderMerReturnMoneyApply/orderMerReturnMoneyApplyList.jsp"}}]},{"text":"网关订单管理",'state':'closed',"children":[{"text":"商品订单列表","attributes":{"url":"order/orderProductList.jsp"}},{"text":"支付订单列表","attributes":{"url":"order/orderPayList.jsp"}},{"text":"银行订单列表","attributes":{"url":"order/orderBankList.jsp"}}]},{"text":"财务结算",'state':'closed',"children":[{"text":"商户结算列表","attributes":{"url":"finacial/finacialOrderProductList.jsp"}},{"text":"银行对账列表","attributes":{"url":"finacial/finacialOrderPayList.jsp"}},{"text":"账户余额统计","attributes":{"url":"template/templateList.jsp?keyRandom=20150423144439356"}},{"text":"汇总表","attributes":{"url":"template/templateList.jsp?keyRandom=20150423145252903"}},{"text":"收单商户运营明细表","attributes":{"url":"template/templateList.jsp?keyRandom=20150423145707996"}},{"text":"商户结算单","attributes":{"url":"template/templateList.jsp?keyRandom=20150423145934153"}},{"text":"银行对账单","attributes":{"url":"template/templateList.jsp?keyRandom=20150423150511418"}}]},{"text":"划款处理",'state':'closed',"children":[]},{"text":"自营产品订单管理",'state':'closed',"children":[{"text":"自营产品订单列表","attributes":{"url":"order/orderProductMyList.jsp"}},{"text":"手机充值订单列表","attributes":{"url":"mobile/mobileInfoList.jsp"}},{"text":"油卡充值订单列表","attributes":{"url":"oilCard/oilCardInfoList.jsp"}}]},{"text":"自营产品通道管理",'state':'closed',"children":[{"text":"手机充值通道管理","attributes":{"url":"channel/mobileChannelChange.jsp"}}]},{"text":"test订单管理",'state':'closed',"children":[]},{"text":"弘康管理",'state':'closed',"children":[]},{"text":"风控管理",'state':'closed',"children":[{"text":"风控规则管理","attributes":{"url":"systemMag/systemMag_queryRiskRule.action"}},{"text":"风控黑名单","attributes":{"url":"systemMag/riskBlackList.jsp"}},{"text":"风控记录列表","attributes":{"url":"systemMag/riskPayOrderList.jsp"}}]},{"text":"退出系统",'state':'closed',"children":[{"text":"退出","attributes":{"url":"logout"}}]}]
	/**
	 * 通过userId查菜单结构（一般首页菜单使用）
	 * @param userId
	 * @return
	 */
	@Override
	public Result queryMenusByUser(long userId) {

		Result result = new Result();
		A2User user = a2UserDao.fetch(userId);
		List<A2Role> roleList = user.getA2RoleList();

		//当前用户拥有的所有菜单
		List<A3Menu> myMenuList = new ArrayList<>();
		for(A2Role role : roleList){
			for(A3MenuMy menuMy:role.getA3MenuMyList()){
				A3Menu menu = menuMy.getA3Menu();
				//将所有menu的parentMenu放入myMenuList中
				genParentMenu(menu,myMenuList);
				if(menu.getDeleteFlag() == 1){continue;}
				if(myMenuList.contains(menu)){continue;}
				myMenuList.add(menu);
			}
		}

		//排序
		Collections.sort(myMenuList, new Comparator<A3Menu>() {
			@Override
			public int compare(A3Menu o1, A3Menu o2) {
				return o1.getSort() - o2.getSort();
			}
		});

		//找第一级ParentMenu
		List<A3Menu> myMenuParentList = new ArrayList<>();
		for(A3Menu menu : myMenuList){
			if(menu.getA3MenuParent() == null){
				myMenuParentList.add(menu);
			}
		}

		//递归生成树，存储在jsonObject里
		JSONObject jsonObject = new JSONObject();
		genMenuJsonTreeByUser(jsonObject, myMenuParentList, myMenuList);
		JSONArray jsonArray = jsonObject.getJSONArray("children");
		List list = jsonArray.toList();
		String menuJson = jsonArray.toString();
		//.out.println("<=====menuJson4FirstMenuPage:"+menuJson);

		result.getResultMap().put("list",list);

		return result.success();
	}

	//将所有menu的parentMenu放入myMenuList中
	private void genParentMenu(A3Menu menu,List<A3Menu> myMenuList){
		A3Menu menuParent = menu.getA3MenuParent();
		if(menuParent==null)return;
		if(!myMenuList.contains(menuParent)){
			myMenuList.add(menuParent);
		}
		genParentMenu(menuParent, myMenuList);
	}

	/**
	 * 递归Menu生成树
	 * @param jsonObject:当前用户拥有的所有菜单 转换成json模式
	 * @param myMenuParentList：传入的上一级菜单列表
	 * @param myMenuList:当前用户拥有的所有菜单
	 */
	private void genMenuJsonTreeByUser(JSONObject jsonObject,List<A3Menu> myMenuParentList,List<A3Menu> myMenuList){
		JSONArray jsonArray = new JSONArray();
		jsonObject.put("children", jsonArray);

		for(A3Menu menu: myMenuParentList){
			long id = menu.getId();
			long menuParentId = 0;
			if(menu.getA3MenuParent()!=null){
				menuParentId = menu.getA3MenuParent().getId();
			}
			int deleteFlag = menu.getDeleteFlag();
			if(deleteFlag==1){
				continue;
			}
			String text = menu.getText();
			String url = menu.getUrl();
			int type = menu.getType();
			int hasDataLimit = menu.getHasDataLimit();
			String iconClass = menu.getIconClass();
			int sort = menu.getSort();

			//json
			JSONObject jsonObjectSon = new JSONObject();
			jsonObjectSon.put("id",id);
			jsonObjectSon.put("menuParentId",menuParentId);
			jsonObjectSon.put("text",text);
			jsonObjectSon.put("name",text);
			jsonObjectSon.put("url", url==null?"":url);
			jsonObjectSon.put("type", type);
			jsonObjectSon.put("iconClass", iconClass);
			jsonObjectSon.put("hasDataLimit", hasDataLimit);
			jsonObjectSon.put("sort", sort);
			jsonArray.put(jsonObjectSon);

			//取当前menu的下级menu
			List<A3Menu> menuSonList = new ArrayList<>();
			for(A3Menu menu1 : myMenuList){
				if(menu1.getA3MenuParent()!=null && menu1.getA3MenuParent().getId() == menu.getId()){
					menuSonList.add(menu1);
				}
			}

			if(menuSonList.size()==0){continue;}
			if(type >= 10){continue;}
			genMenuJsonTreeByUser(jsonObjectSon, menuSonList, myMenuList);
		}
	}


	/**
	 * 权限管理，通过url查所有权限列表
	 * @param url
	 * @return
	 */
	@Override
	public Set<String> getMenu2AuthListByUrl(String url){
		Set<String> menuAuthList = new HashSet<String>();
		Search search = new Search();
		search.addFilterEqual("url", url);

		List<A3Menu> menuList = a3MenuDao.search(search);
		for(A3Menu menu : menuList){
			menuAuthList.add(String.valueOf(menu.getId()));
		}
		////.out.println("<========menuAuthList:"+menuAuthList);
		return menuAuthList;
	}

	/**
	 * 权限管理，登录时调用
	 * @param loginname
	 * @return
	 */
	@Override
	public A2UserDto getUserByLoginname(String loginname){
		A2UserDto userDto = new A2UserDto();

		Search search = new Search();
		search.addFilterEqual("loginName", loginname);
		A2User user = (A2User)a2UserDao.searchUnique(search);
		//a2UserDao.refresh(user);
		////.out.println("========:"+user.getName());
		if(user == null){
			return null;
		}

		DTOAssembler ass = DTOAssembler.newAssembler(A2UserDto.class);
		ass.assembleDto(userDto, user, null, null);

		//取用户权限列表
		for(A2Role role : user.getA2RoleList()){
			a2RoleDao.refresh(role);
			for(A3MenuMy menuMy : role.getA3MenuMyList()){
				A3Menu menu = menuMy.getA3Menu();
				userDto.getMenu2AuthList().add(String.valueOf(menu.getId()));
				//页面功能点，如：查询; role-menu link table 中存储的type是20=function
				for(A3Menu menu1:menu.getA3MenuSonList()){
					userDto.getMenu2AuthList().add(String.valueOf(menu1.getId()));
				}
				genParentMenuUrl(menu,userDto);
			}
		}
		////.out.println("userDto.getMenu2AuthList():"+userDto.getMenu2AuthList());

		return userDto;
	}

	private void genParentMenuUrl(A3Menu menu, A2UserDto userDto){
		A3Menu parentMenu = menu.getA3MenuParent();
		if(parentMenu == null){
			return;
		}
		userDto.getMenu2AuthList().add(String.valueOf(parentMenu.getId()));
		genParentMenuUrl(parentMenu,userDto);
	}


	/**
	 * 源码模式生成二级菜单
	 * @param paramMap
	 * long _templateTableId = (Long)paramMap.get("_templateTableId");
	 * long menuIdParent = (Long)paramMap.get("menuIdParent");
	 * String menuName = (String)paramMap.get("menuName");
	 * long userId = (Long)paramMap.get("userId");
	 * @return
	 */
	@Override
	public Result template2menuSourceCode(Map<String,Object> paramMap) {
		long _templateTableId = (Long)paramMap.get("_templateTableId");
		long menuIdParent = (Long)paramMap.get("menuIdParent");
		String menuName = (String)paramMap.get("menuName");
		long userId = (Long)paramMap.get("userId");

		Result result = new Result();
		//取模板表
		A1TemplateTable table = a1TemplateTableDao.fetch(_templateTableId);
		String tableNameShow = table.getTableNameShow();
		String keyRandom = table.getKeyRandom();
		String tableName = table.getTableName();
		String tableNameProperty = switch2Property(tableName);
		//menu2Name
		menuName = StringUtils.isNull(menuName)?tableNameShow:menuName;

		Result result1=checkMenuName(menuName);
		if(!result1.isSuccess()){
			return result1;
		}

		//取一级菜单
		A3Menu menuParent = a3MenuDao.fetch(menuIdParent);
		//生成二级菜单
		A3Menu menu = new A3Menu();
		menu.setText(menuName);
		menu.setA3MenuParent(menuParent);
		menu.setUrl(Config.url_queryPage_sc.replaceAll("#pageName#", tableNameProperty));
		menu.setType(10);//0=menu; 10=leave menu; 20=function 30=function url
		menu.setKeyRandom(table.getKeyRandom());
		a3MenuDao.create(menu);
		//生成功能资源
		A3Menu funQuery = new A3Menu();
		funQuery.setUrl(Config.url_queryAction_sc.replaceAll("#pageName#", tableNameProperty));
		funQuery.setText("查询");
		funQuery.setType(20);
		funQuery.setA3MenuParent(menu);
		a3MenuDao.create(funQuery);
		//当前用户直接授权
		setMenu2Role(userId, funQuery);
		//query detail
		A3Menu fun1 = new A3Menu();
		fun1.setUrl(Config.url_addeditPage_sc.replaceAll("#pageName#", tableNameProperty));
		fun1.setText("details");
		fun1.setType(30);
		fun1.setA3MenuParent(funQuery);
		a3MenuDao.create(fun1);
		//生成添加的资源
		A3Menu funAdd = new A3Menu();
		funAdd.setUrl(Config.url_addAction_sc.replaceAll("#pageName#", tableNameProperty));
		funAdd.setText("添加");
		funAdd.setType(20);
		funAdd.setA3MenuParent(menu);
		a3MenuDao.create(funAdd);
		//当前用户直接授权
		setMenu2Role(userId, funAdd);
		//生成修改的资源
		A3Menu funEdit = new A3Menu();
		funEdit.setUrl(Config.url_editAction_sc.replaceAll("#pageName#", tableNameProperty));
		funEdit.setText("修改");
		funEdit.setType(20);
		funEdit.setA3MenuParent(menu);
		a3MenuDao.create(funEdit);
		//当前用户直接授权
		setMenu2Role(userId, funEdit);
		//生成删除的资源
		A3Menu funRemove = new A3Menu();
		funRemove.setUrl(Config.url_removeAction_sc.replaceAll("#pageName#", tableNameProperty));
		funRemove.setText("删除");
		funRemove.setType(20);
		funRemove.setA3MenuParent(menu);
		a3MenuDao.create(funRemove);
		//当前用户直接授权
		setMenu2Role(userId, funRemove);


		//加入源码配置文件
		A3jeeCodingDto jeeCodingDtoParam = new A3jeeCodingDto();
		jeeCodingDtoParam.setModelName(tableNameProperty);
		Result resultSearch = a3jeeCodingService.pagination(jeeCodingDtoParam,null);
		int total = (Integer)resultSearch.getResultMap().get("total");
		if(total>0){
			throw new RuntimeException("记录已存在，可能菜单以生成，请通过菜单生成源码");
		}
		A3jeeCodingDto jeeCodingDto = new A3jeeCodingDto();
		jeeCodingDto.setModelName(tableNameProperty);
		jeeCodingDto.setSort("0");
		jeeCodingDto.setDeleteflag("0");
		jeeCodingDto.setCompanyId("0");
		jeeCodingDto.setCreatemanId("0");
		jeeCodingDto.setModifymanId("0");
		Result result2 = a3jeeCodingService.addData(jeeCodingDto);


		return result2.success();
	}


	/**
	 * 字段转成属性
	 * @param columnName
	 * @return
	 */
	public static String switch2Property(String columnName){
		////.out.println(columnName.matches("c+"));
		if (columnName.contains("_")){
			Pattern pattern = Pattern.compile("_[a-z,0-9]");
			Matcher matcher = pattern.matcher(columnName);
			while(matcher.find()){
				String old = matcher.group();
				String new1 = matcher.group().toUpperCase();
				columnName = columnName.replaceAll(old, new1.replace("_",""));
			}
		}
		return columnName;
	}

	private Result checkMenuName(String menuName){
		Result result = new Result();
		Search search = new Search();
		search.addFilterEqual("text", menuName);
		search.addFilterEqual("deleteFlag", "0");
		int count = a3MenuDao.count(search);
		if(count > 0){
			return result.fault("已存在二级菜单，可删除原菜单后继续，或修改菜单名称："+menuName);
		}
		return result.success();
	}

	/**
	 * 当前用户直接授权
	 * @return
	 */
	private boolean setMenu2Role(long userId, A3Menu menu){
		A2User user = a2UserDao.fetch(userId);
		A2Role a2Role = user.getA2RoleList().get(0);
		A3MenuMy menuMy = new A3MenuMy();
		menuMy.setA2Role(a2Role);
		menuMy.setA3Menu(menu);
		menuMy.setDataLimitType(0);
		a3MenuMyDao.create(menuMy);
		return true;
	}

	/**
	 * 生成模板菜单
	 * @param paramMap
	 * long _templateTableId = (Long)paramMap.get("_templateTableId");
	 * long menuIdParent = (Long)paramMap.get("menuIdParent");
	 * String menuName = (String)paramMap.get("menuName");
	 * long userId = (Long)paramMap.get("userId");
	 * @return
	 */
	@Override
	public Result template2menu(Map<String,Object> paramMap) {
		long _templateTableId = (Long)paramMap.get("_templateTableId");
		long menuIdParent = (Long)paramMap.get("menuIdParent");
		String menuName = (String)paramMap.get("menuName");
		long userId = (Long)paramMap.get("userId");

		Result result = new Result();
		//取模板表
		A1TemplateTable table = a1TemplateTableDao.fetch(_templateTableId);
		String tableNameShow = table.getTableNameShow();
		String keyRandom = table.getKeyRandom();
		//menu2Name
		menuName = StringUtils.isNull(menuName)?tableNameShow:menuName;

		Result result1=checkMenuName(menuName);
		if(!result1.isSuccess()){
			return result1;
		}

		//取一级菜单
		A3Menu menuParent = a3MenuDao.fetch(menuIdParent);
		//生成二级菜单
		A3Menu menu = new A3Menu();
		menu.setText(menuName);
		menu.setA3MenuParent(menuParent);
		menu.setUrl(Config.url_queryPage + keyRandom);
		menu.setType(10);//0=menu; 10=leave menu; 20=function 30=function url
		a3MenuDao.create(menu);
		//生成功能资源
		A3Menu funQuery = new A3Menu();
		funQuery.setUrl(Config.url_queryAction+keyRandom);
		funQuery.setText("查询");
		funQuery.setType(20);
		funQuery.setA3MenuParent(menu);
		a3MenuDao.create(funQuery);
		//当前用户直接授权
		setMenu2Role(userId, funQuery);
		//query detail
		A3Menu fun1 = new A3Menu();
		fun1.setUrl(Config.url_addeditPage + keyRandom);
		fun1.setText("details");
		fun1.setType(30);
		fun1.setA3MenuParent(funQuery);
		a3MenuDao.create(fun1);
		//生成添加的资源
		A3Menu funAdd = new A3Menu();
		funAdd.setUrl(Config.url_addAction+keyRandom);
		funAdd.setText("添加/修改");
		funAdd.setType(20);
		funAdd.setA3MenuParent(menu);
		a3MenuDao.create(funAdd);
		//当前用户直接授权
		setMenu2Role(userId, funAdd);
		//生成删除的资源
		A3Menu funRemove = new A3Menu();
		funRemove.setUrl(Config.url_removeAction + keyRandom);
		funRemove.setText("删除");
		funRemove.setType(20);
		funRemove.setA3MenuParent(menu);
		a3MenuDao.create(funRemove);
		//当前用户直接授权
		setMenu2Role(userId, funRemove);


		return result.success();
	}

	/**
	 *
	 * @param paramMap
	 * long _templateTableId = (Long)paramMap.get("_templateTableId");
	 * long menuIdParent = (Long)paramMap.get("menuIdParent");
	 * String menuName = (String)paramMap.get("menuName");
	 * String pageType = (String)paramMap.get("pageType");
	 * long userId = (Long)paramMap.get("userId");
	 * @return
	 */
	@Override
	public Result template2menu4Chart(Map<String,Object> paramMap) {
		long _templateTableId = (Long)paramMap.get("_templateTableId");
		long menuIdParent = (Long)paramMap.get("menuIdParent");
		String menuName = (String)paramMap.get("menuName");
		String pageType = (String)paramMap.get("pageType");
		long userId = (Long)paramMap.get("userId");

		Result result = new Result();
		//取模板表
		A1TemplateTable table = a1TemplateTableDao.fetch(_templateTableId);
		String tableNameShow = table.getTableNameShow();
		String keyRandom = table.getKeyRandom();
		//menu2Name
		menuName = StringUtils.isNull(menuName)?tableNameShow:menuName;

		Result result1=checkMenuName(menuName);
		if(!result1.isSuccess()){
			return result1;
		}

		//取一级菜单
		A3Menu menuParent = a3MenuDao.fetch(menuIdParent);

		String menuUrl = "";
		String funUrl = "";
		if("chartPie".equals(pageType)){
			menuUrl = Config.url_chartPie;
			menuUrl = menuUrl.replace(":_keyRandom", keyRandom);
			funUrl = Config.url_chartPieAction;
			funUrl = funUrl.replace(":_keyRandom", keyRandom);
		}else{
			menuUrl = Config.url_chartMS;
			menuUrl = menuUrl.replace(":_keyRandom", keyRandom);
			menuUrl = menuUrl.replace(":_chartType", pageType);
			funUrl = Config.url_chartMSAction;
			funUrl = funUrl.replace(":_keyRandom", keyRandom);
		}

		//生成二级菜单
		A3Menu menu = new A3Menu();
		menu.setText(menuName);
		menu.setA3MenuParent(menuParent);
		menu.setUrl(menuUrl);
		menu.setType(10);
		a3MenuDao.create(menu);
		//生成功能资源
		A3Menu fun = new A3Menu();
		fun.setUrl(funUrl);
		fun.setText("查询");
		fun.setType(20);
		fun.setA3MenuParent(menu);
		a3MenuDao.create(fun);

		//当前用户直接授权
		setMenu2Role(userId, menu);

		return result.success();
	}


	/**
	 *
	 * @param paramMap
	 * long _templateColumnId = (Long)paramMap.get("_templateColumnId");
	 * long menuIdParent = (Long)paramMap.get("menuIdParent");
	 * String menuName = (String)paramMap.get("menuName");
	 * String pageType = (String)paramMap.get("pageType");
	 * String columnName = (String)paramMap.get("columnName");
	 * long userId = (Long)paramMap.get("userId");
	 * @return
	 */
	@Override
	public Result template2menu4ChartSingle(Map<String,Object> paramMap) {
			long _templateColumnId = (Long)paramMap.get("_templateColumnId");
			long menuIdParent = (Long)paramMap.get("menuIdParent");
			String menuName = (String)paramMap.get("menuName");
			String pageType = (String)paramMap.get("pageType");
			String columnName = (String)paramMap.get("columnName");
			long userId = (Long)paramMap.get("userId");


			Result result = new Result();
		//取列
		A1TemplateColumn templateColumn = a1TemplateColumnDao.fetch(_templateColumnId);
		//取模板表
		A1TemplateTable table = templateColumn.getA1TemplateTable();
		String tableNameShow = table.getTableNameShow();
		String keyRandom = table.getKeyRandom();
		//menu2Name
		menuName = StringUtils.isNull(menuName)?tableNameShow:menuName;

		Result result1=checkMenuName(menuName);
		if(!result1.isSuccess()){
			return result1;
		}

		//取一级菜单
		A3Menu menuParent = a3MenuDao.fetch(menuIdParent);

		String menuUrl = "";
		String funUrl = "";
		menuUrl = Config.url_chartSingle;
		menuUrl = menuUrl.replace(":_keyRandom", keyRandom);
		menuUrl = menuUrl.replace(":_chartType", pageType);
		menuUrl = menuUrl.replace(":_chartColumn", columnName);
		funUrl = Config.url_chartSingleAction;
		funUrl = funUrl.replace(":_keyRandom", keyRandom);

		//生成二级菜单
		A3Menu menu = new A3Menu();
		menu.setText(menuName);
		menu.setA3MenuParent(menuParent);
		menu.setUrl(menuUrl);
		menu.setType(10);
		a3MenuDao.create(menu);
		//生成功能资源
		A3Menu fun = new A3Menu();
		fun.setUrl(funUrl);
		fun.setText("查询");
		fun.setType(20);
		fun.setA3MenuParent(menu);
		a3MenuDao.create(fun);

		//当前用户直接授权
		setMenu2Role(userId, menu);

		return result.success();
	}

}

